<?php

include_once('Commons.php');
include_once('checks.php');

$action = param('_ac');
$email = trim(param('_email'));

$currentUser = getCurrentUser();
$latestProfile = getLatestProfile( $currentUser['id'] );


/**
 * Email verification during all steps
 */
if ( $action=='new' || $action=='register')
{
	if ( empty($email) )
		$usernameerror = getTerm('sign_in', 'empty_email_address');
	
	elseif (!validate_email($email, true) )
		$usernameerror = getTerm('sign_in', 'bad_email_address');
		
	else
	{
		$rh = query("SELECT id FROM user WHERE email='$email';");
		
		if ( mysql_num_rows($rh)>0 )
			$usernameerror = getTerm('sign_in', 'email_already_exists');
	}
		
	if ( ! empty($usernameerror) )
		$action = '';
}


if ( $action=="register" )
{
	$username = param('_username');
	$country = param('_country');
	$city = param('_city');
	$birthday = param('_birthday');
	$birthmonth = param('_birthmonth');
	$birthyear = param('_birthyear');
	$gender = param('_gender');
	$description = param('_description');
	$continent = param('_continent');
	
	
	$birthdate = sprintf('%04d-%02d-%02d', $birthyear, $birthmonth, $birthday);
	$today = gmdate('Y-m-d');
	
	if ( empty($birthday) ||  empty($birthmonth) ||  empty($birthyear) || !checkdate($birthmonth, $birthday, $birthyear) || $birthyear<1900 || strlen($birthyear)!=4 )
		$birthdayerror = getTerm('profile', 'invalid_birthday');
		
	elseif ( strcmp($birthdate, $today)>0 )
		$birthdayerror = getTerm('profile', 'invalid_birthday');
		
	if ( empty($username) )
		$usernameerror = getTerm('profile', 'empty_username');
		
	elseif ( ! preg_match('/^\w+$/', $username) )
		$usernameerror = getTerm('profile', 'invalid_username');
	
	else
	{
		$usernamelow = strtolower($username);
		$rh = query("SELECT LOWER(username) FROM user WHERE username LIKE '". $username ."%';");
		
		$usernames = array();
		
		while ( $row = mysql_fetch_array($rh) )
			array_push($usernames, $row[0]);
		
		if ( in_array($usernamelow, $usernames) )
		{
			$usernameerror = fill( getTerm('profile','username_already_exists') , $username );
			
			$i=0;
			do
				$i++;
			while ( in_array("$usernamelow$i", $usernames) );
			
			$username = "$username$i";
		}
	}
	
	
	if ( empty($country) )
		$countryerror = getTerm('profile', 'empty_country');
	else
	{
		$rh = query("SELECT id FROM region WHERE id='$country' AND is_country=1;");
		if ( mysql_num_rows($rh)!=1 )
			$countryerror = getTerm('profile', 'empty_country');
	}
	
	
	if ( empty($city) )
		$cityerror = getTerm('profile', 'empty_city');
	
	
	if ( empty($description) )
		$descriptionerror = getTerm('profile', 'empty_description');
		
			
	if ( ! in_array($gender, array('female', 'male') ) )
		$gendererror = getTerm('profile', 'empty_gender');

	if ($description) {
		$rej = 0;
		if (strlen($description) < 50) {
			$descriptionerror = getTerm('profile', 'small_description');
		}
		if (find_multiphrases($description)) {
			$descriptionerror = getTerm('checks', 'repeated_description');
			$rej = 1;
		}

		if (check_string($description, $social_sites)) {
			$descriptionerror = getTerm('checks', 'social_sites');
			$rej = 1;
		}

		if (find_email($description)) {
			$descriptionerror = getTerm('checks', 'email_addr');
			$rej = 1;
		}

		if (find_websites($description)) {
			$descriptionerror = getTerm('checks', 'website_addr');
			$rej = 1;
		}

		if (find_phone($description)) {
			$descriptionerror = getTerm('checks', 'phone_num');
			$rej = 1;
		}
		if ($rej > 0) {
			query("INSERT INTO rejects (email,rejects) VALUES (LOWER('$email'),1) ON DUPLICATE KEY UPDATE rejects=rejects+1;");
		}
	}

		
	if ( ! ( empty($birthdayerror) && empty($usernameerror) && empty($countryerror) && empty($cityerror) && empty($gendererror) && empty($descriptionerror) ) )
		$action = 'new';
		
	else {

# registration data passed, starting content checks
		$ip = get_ip_address();
		$country_code = ip_to_country($ip);

		if (country_blacklisted($bad_countries, $country, $country_code)) {
			$action = 'finallogin';
		} else {

			$rnum = query("SELECT rejects FROM rejects WHERE email=LOWER('$email');");
			list($rejects) = mysql_fetch_array($rnum);

			$l2checks = 0;

			$country_check = match_country($country, $country_code);	# force level2 checks if more than 3 rejects or country picked is not actual ip country
			if ($country_check && $rejects > 3) {
				$action = 'finallogin';
			} else {
				if ($country_check || $rejects > 3) { 
					$l2checks = 1;
				}
# checks
				$failed = 0;
											# level 2
				if ($l2checks) {
					if (level2_check($description, true)) {
						$failed = 2;
					}
				} else {
					if (level3_check($description)) {
						$failed = 3;
					}
				}


			$password = '';
		
			$letters = array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
			for ( $i=0 ; $i<6 ; $i++ )
				$password .= $letters[ rand(0,count($letters)) ];

			query("INSERT INTO user (username,email,password,since) VALUES ('$username','$email','$password',NOW());");
		
			$userId = mysql_insert_id();
		

			$parameters = array($username,$password);
			sendMail('register',$email,$username,$parameters);
		
		
			modifyProfile($userId, $country, 0, $city, $gender, $description, $birthdate, $continent);

			if ($region = country_to_region($country)) {
				query("UPDATE profile SET continent ='$region' WHERE user='$userId';");
			}

# refuse
			if ($failed > 0) {
				query("UPDATE profile SET current=0 WHERE user='$userId';");
				query("UPDATE profile SET status=1 WHERE user='$userId';");
				query("UPDATE profile SET valid = NULL WHERE user='$userId';");

				$parameters = array($username);
				sendMail('autorefuse', $email, $username, $parameters);

			} else {
# approve
				query("UPDATE profile SET valid=1, current=1 WHERE user='$userId';");

				$parameters = array($username);
				sendMail('autovalidate', $email, $username, $parameters);
				logEvent(0, '', $userId);
			}

			$action = 'finallogin';
			exit;
			}
		}       
	}
}
elseif ( $action=='finalize' || $action=='login' )
{
	$email = $_POST['_email'];
	$password = $_POST['_password'];
		
	$rh = query("SELECT id,PASSWORD(password) FROM user WHERE email='$email' AND password='$password';");
	
	debug('Résultat : '. mysql_num_rows($rh) );
	
	if ( mysql_num_rows($rh)==0 )
	{
		$usernameerror = fill( getTerm('sign_in', 'bad_username_password'), formatUrl('/lost-password/') );
		$passworderror = getTerm('sign_in', 'bad_password');
		
		$action = $action=='finalize' ? 'finallogin' : '' ;
	}
	else
	{
		list($user, $password) = mysql_fetch_array($rh);
		
		debug('Id utilisateur : '. $user);
		
		$_SESSION['user'] = $user;
		
		setcookie('email', $email, time()+60*60*24*600, '/');
		//setcookie('password', $password, time()+60*60*24*600, '/');
		
		if ( $action=='login' )
			logEvent(2);
		else
			logEvent(1);
	}
}

if ( $action=='login' || $action=='finalize' )
{
	$url = $_SERVER['REQUEST_URI'];
	
	if ( $url==formatUrl('/signin') )
	{
		$url = $_SESSION['redirectionUrl'];
		$_SESSION['redirectionUrl'] = '';
		
		if ( empty($url) )
		
			$url = formatUrl('/');
	}
	
	redirect($url);
}
elseif ( $action=='finallogin' )
{
	printHeader( getTerm('sign_in', 'finalize_registration') );
	
	print "<div id=\"final-login\"><p>";
	print fill( getTerm('sign_in', 'your_password_has_been_sent') , $email );
	print "</p><form action=\"${_SERVER[REQUEST_URI]}\" method=\"post\">";
	print "<input type=\"hidden\" name=\"_ac\" value=\"finalize\" />";
	print "<input type=\"hidden\" name=\"_email\" value=\"$email\" />";

	print "<div class=\"field". (empty($passworderror) ? '' : ' error') ."\"><label for=\"password\">" . getTerm('sign_in', 'your_password') . "</label>";
	print (empty($passworderror) ? '' : "<div class=\"error-hint\">$passworderror</div>");
	print "<input type=\"password\" id=\"password\" name=\"_password\" /></div>";
	
	print "<div class=\"field\"><input type=\"submit\" value=\"" . getTerm('sign_in', 'finalize') . "\" /></div>";

	print "</form></div>";
}
elseif ( $action=="new" )
{
	printHeader( getTerm('sign_in', 'fill_in_profile') );

	print "<div id=\"fill-profile\"><p>";
	print getTerm('profile', 'you_must_fill_in_your_profile');
	print "</p><form action=\"${_SERVER[REQUEST_URI]}\" method=\"post\">";
	
	print "<div class=\"field". (empty($usernameerror) ? '' : ' error') ."\"><label for=\"username\">" . getTerm('profile', 'choose_username') . "</label>";
	print (empty($usernameerror) ? '' : "<div class=\"error-hint\">$usernameerror</div>");
	print "<input type=\"text\" id=\"username\" name=\"_username\" value=\"$username\" maxlength=\"60\"/>";
	
	print "<input type=\"hidden\" name=\"_ac\" value=\"register\" />";
	print "<input type=\"hidden\" name=\"_email\" value=\"$email\" />";
	
	print "</div>";
	
	$rh = query('SELECT id,name FROM region WHERE is_country=1 ORDER BY name;');
	
	print "<div class=\"field". (empty($countryerror) ? '' : ' error') ."\"><label for=\"country\">" . getTerm('profile', 'your_country') . "</label>";
	print (empty($countryerror) ? '' : "<div class=\"error-hint\">$countryerror</div>");
	print "<select name=\"_country\" id=\"country\">";
	while ( $countri = mysql_fetch_array($rh) )

		print "<option value=\"$countri[0]\"". ($countri[0]==$country ? ' selected="selected"' : '') .">". getTerm('country', $countri[1]) ."</option>";

	print "</select>";
	print "</div>";
	
	print "<div class=\"field". (empty($cityerror) ? '' : ' error') ."\"><label for=\"city\">" . getTerm('profile', 'your_city') . "</label>";
	print (empty($cityerror) ? '' : "<div class=\"error-hint\">$cityerror</div>");
	print "<input type=\"text\" id=\"city\" name=\"_city\" value=\"". stripslashes($city) ."\" maxlength=\"32\"/>";
	print "</div>";
	
	$months = array('january','february','march','april','may','june','july','august','september','october','november','december');
	$datepattern = getTerm('time', 'simpledatepattern');
	$birthdayhtml = '';

	for ( $j=0 ; $j<strlen($datepattern) ; $j++ )
	{
		$current = substr($datepattern, $j, 1);

		if ( $current=='%' )
		{
			$j++;
			$current = substr($datepattern, $j, 1);
			
			switch ($current)
			{
				case 'd' :
					$birthdayhtml .= "<select id=\"birthday\" name=\"_birthday\">";
					for ( $i=1 ; $i<=31 ; $i++ )
						$birthdayhtml .= "<option value=\"$i\"". ($i==$birthday ? ' selected="selected"' : '') .">$i</option>";
					$birthdayhtml .= "</select>";
					if ( empty($first) ) $first='birthday';
					break;
					
				case 'M' :							
					$birthdayhtml .= "<select id=\"birthmonth\" name=\"_birthmonth\">";
					for ( $i=1 ; $i<=12 ; $i++ )
						$birthdayhtml .= "<option value=\"$i\"". ($i==$birthmonth ? ' selected="selected"' : '') .">". getTerm('time', $months[$i-1]) ."</option>";
					$birthdayhtml .= "</select>";
					if ( empty($first) ) $first='birthmonth';
					break;
				
				case 'y' :
					if ( empty($birthyear) ) $birthyear=19;
					
					$birthdayhtml .= "<select id=\"birthyear\" name=\"_birthyear\">";
					$birthdayhtml .= "<option value=\"\">----</option>";
					$start = date("Y", strtotime("-4 years"));
					$end = 1901;
					$tmp_count = 0;
					while ($start>=$end && $tmp_count<150) {
						$birthdayhtml .= "<option value=\"$start\"". ($start==$birthyear ? ' selected="selected"' : '') .">$start</option>";
						$start--;
					}
					$birthdayhtml .= "</select>";

					if ( empty($first) ) $first='birthyear';
					break;
					
				default :
					$birthdayhtml .= "%$current";
			}
		}
		else
			$birthdayhtml .= $current;
	}

	print "<div class=\"field". (empty($birthdayerror) ? '' : ' error') ."\"><label for=\"$first\">" . getTerm('profile', 'your_birthday') . "</label>";
	print (empty($birthdayerror) ? '' : "<div class=\"error-hint\">$birthdayerror</div>");
	print $birthdayhtml;
	print "</div>";
	

	print "<div class=\"field". (empty($gendererror) ? '' : ' error') ."\"><label for=\"gender\">" . getTerm('profile', 'your_gender') . "</label>";
	print "<select name=\"_gender\" id=\"gender\">";
	foreach ( array('female','male') as $gen )

		print "<option value=\"$gen\"". ($gender==$gen ? ' selected="selected"' : '') .">". getTerm('profile', $gen) ."</option>";

	print "</select>";
	print (empty($gendererror) ? '' : "<div class=\"error-hint\">$gendererror</div>") ."</div>";

	print "<div class=\"field". (empty($descriptionerror) ? '' : ' error') ."\"><label for=\"description\">" . getTerm('profile', 'your_description') . "</label>";
	print (empty($descriptionerror) ? '' : "<div class=\"error-hint\">$descriptionerror</div>");
	print "<textarea id=\"description\" name=\"_description\">". stripslashes($description) ."</textarea>";
	print "<div class=\"hint\"><a name=\"recommendations\"></a>". getTerm('profile', 'description_recommendations') ."</div></div>";
	
	print "<div class=\"field\"><input type=\"submit\" value=\"" . getTerm('profile', 'save_profile') . "\" /></div>";
	print "</form></div>";

	//start of region code
	if ($region = country_to_region($country)) {
		query("UPDATE profile SET continent ='$region' WHERE user=${currentUser[id]};");
	}

	//finish of region code
	
}
else
{
	if ( empty($email) && array_key_exists('email', $_COOKIE) )
		$email = $_COOKIE['email'];

	printHeader( getTerm('sign_in', 'sign_in') );
	
	print "<div id=\"sign-in\"><form action=\"${_SERVER[REQUEST_URI]}\" method=\"post\">";
	
	if ( $_SERVER['REQUEST_URI']!=formatUrl('/signin') )
	{
		print "<p>";
		print getTerm('sign_in', 'you_must_sign_in');
		print "</p>";
	}
	else if ( $_SERVER['HTTP_REFERER']!=formatUrl('/signin') )
	{
		$_SESSION['redirectionUrl'] = $_SERVER['HTTP_REFERER'];
	}
	
	print "<div class=\"field". (empty($usernameerror) ? '' : ' error') ."\"><label for=\"email\">" . getTerm('sign_in', 'your_email') . "</label>";
	print (empty($usernameerror) ? '' : "<div class=\"error-hint\">$usernameerror</div>");
	print "<input type=\"text\" id=\"email\" name=\"_email\" value=\"$email\" />";
	print "</div>";
	
	print '<div><input type="radio" name="_ac" value="login" id="ac-registered"'. ( !empty($email) ? ' checked="checked"' : '' ) .' /><label for="ac-registered">'. getTerm('sign_in', 'registered_user') .'</label></div>';

	print "<div class=\"field\"><label for=\"password\">" . getTerm('sign_in', 'your_password') . "</label>";
	print "<input type=\"password\" id=\"password\" name=\"_password\" /> <a href=\"". formatUrl('/lost-password/') ."\">". getTerm('sign_in', 'lost_password') ."</a></div>";

	print '<div><input type="radio" name="_ac" value="new" id="ac-new"'. ( empty($email) ? ' checked="checked"' : '' ) .' /><label for="ac-new">'. getTerm('sign_in', 'new_user') .'</label></div>';
	
	print "<div class=\"field\"><input type=\"submit\" value=\"" . getTerm('sign_in', 'sign_in_button') . "\" /></div>";
	print "</form></div>";
}

				print '<script type="text/javascript"><!--
google_ad_client = "pub-2652372001711469";
/* Profile - Bottom */
google_ad_slot = "4748431563";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>' ;	
	
printFooter(0);


exit();


function country_to_region($cid) {
$regions = array(
	"1" => array("224", "38", "139", "182", "225"), 
	"2" => array("7", "9", "12", "16", "19", "24", "31", "40", "60", "61", "86", "87", "89", "94", "107", "135", "144", "151", "173", "180", "181", "183", "214", "218", "233"), 
	"3" => array("10", "22", "26", "30", "43", "47", "52", "63", "65", "70", "75", "93", "96", "155", "165", "167", "168", "201", "226", "230"), 
	"4" => array("5", "14", " 21", "58", "73", "74", "81", "83", "106", "123", "125", "126", "133", "142", "152", "161", "172", "185", "198", "204", "205", "229", "215"), 
	"5" => array("2", "11", "15", "20", "27", "33", "55", "57", "68", "80", "84", "98", "118","124", "127", "141", "171", "176", "177", "192", "193", "221", "236"), 
	"6" => array("3", "6", "23", "28", "34", "35", "37", "39", "41", "42", "48", "50", "54", "59", "64", "66", "67", "69", "78", "79", "82", "91", "92", "111", "121", "128", "129", "132", "136", "137", "138", "145", "146", "148", "156", "157", "178", "179", "188", "189", "190", "195", "196", "200", "203", "209", "211", "215", "220", "237", "238", "131", "122"), 
	"7" => array("17", "56", "102", "103", "109", "115", "117", "162", "163", "174", "187", "206", "216", "222", "235"), 
	"8" => array("1", "18", "25", "32", "36", "44", "88", "90", "97", "100", "101", "105", "108", "110", "113", "114", "116", "117", "130", "143", "150", "169", "191", "199", "207", "208", "210", "217", "227", "231"), 
	"9" => array("223", "85", "99", "104", "202"), 
	"10" => array("4", "8", "13", "51", "72", "76","112", "134", "164", "166", "194", "213", "219", "228", "234"), 
);

	foreach ($regions as $region => $ids) {
		if (in_array($cid, $ids)) {
			return $region;
		}
	}
}


?>
